package com.sh.data.engine.domain.feign.Service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sh.data.engine.domain.Isfd.domain.LoginData;
import com.sh.data.engine.domain.Isfd.domain.LoginVo;
import com.sh.data.engine.domain.config.IsfdRequestConfig;
import com.sh.data.engine.domain.feign.FeignGenerateToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.sh.data.engine.common.constants.Constants.ISFD_TOKEN_CACHE_EXPIRE_TIME;

@Slf4j
@Service
public class IsfdTokenService {

    @Autowired
    private IsfdRequestConfig isfdRequestConfig;

    @Autowired
    private FeignGenerateToken feignGenerateToken;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void setTokenWithExpiration(String tokenKey, String tokenValue) {
        // 获取操作字符串值的操作对象
        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
        // 设置键值对，并指定过期时间为 30 分钟
        valueOps.set(tokenKey, tokenValue, ISFD_TOKEN_CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    /**
     * 清除指定 key 的缓存
     *
     * @param key 要清除的 Redis 键
     */
    public void deleteCacheByKey(String key) {
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            // 如果键存在，则删除
            redisTemplate.delete(key);
            System.out.println("Key deleted: " + key);
        } else {
            System.out.println("Key does not exist: " + key);
        }
    }

    public String getToken() {
//        deleteCacheByKey("isfdToken");
        String token = redisTemplate.opsForValue().get("isfdToken");
        if (token != null) {
            return token;
        }
        log.info("Fetching new token from remote service...");
        LoginData loginData = LoginData.builder().username(isfdRequestConfig.getUsername()).password(isfdRequestConfig.getPassword()).clientId(isfdRequestConfig.getClientId()).grantType(isfdRequestConfig.getGrantType()).build();
        JSONObject result = feignGenerateToken.getMap(loginData);
        String jsonObject = JSON.toJSONString(result.get("data"));
        LoginVo data = JSONObject.parseObject(jsonObject, LoginVo.class);
        setTokenWithExpiration("isfdToken", data.getAccessToken());
        return data.getAccessToken();
    }
}
